import Koa, { Context } from "koa";
import { router } from "./router";
import bemModel from "./models/backEndManagement";
import bemRoleModel from "./models/bemrole";
import bhRouter from "./router/bh";
import { newsRouter } from "./router/news";
import { weChatrouter } from "./router/wechat";
import { userRouter } from "./router/user";
import bemRouter from "./router/backEndManagement";
import { Server } from "http";
// import { mw, fverify } from "./middleware";
import { geterrorLogger } from "./logger";
import path from "path";
import cors from "koa2-cors";
// import { historyApiFallback } from "koa2-connect-history-api-fallback";
import views from "koa-views";
import json from "koa-json";
import koaBody from "koa-body";
import { dbconnect } from "./utils/db";
import { resp } from "./utils/res";
import serve from "koa-static";
import range from "koa-range";
import mem from "./models/menues";
const app = new Koa();

dbconnect();
const handler = async (ctx: any, next: any) => {
  try {
    await next();
  } catch (error: any) {
    console.log("====================================");
    console.log(error);
    console.log("====================================");
    await ctx.render("error");
  }
  if (parseInt(ctx.status) === 404) {
    if (ctx.url.split("/")[1] == "user") {
      return await ctx.render("rnbh");
    } else if (ctx.url.split("/")[1] == "bh") {
      return await ctx.render("bh");
    }
    await ctx.render("404");
  }
};

app
  // .use(historyApiFallback({
  //   index: './public/rnbh/index.html'
  // }))
  .use(handler)
  .use(json())
  .use(cors())
  .use(range)
  .use(serve(path.join(__dirname, "./public/")))
  .use(serve(path.join(__dirname, "./public/video/")))
  .use(serve(path.join(__dirname, "./public/chatgpt/")))
  .use(serve(path.join(__dirname, "./public/bemimages/")))
  .use(serve(path.join(__dirname, "./public/bh/")))
  .use(serve(path.join(__dirname, "./public/oldbh/")))
  .use(serve(path.join(__dirname, "./public/rnbh/")))
  // .use(mw)
  // .use(fverify) //控制是否使用token验证
  .use(
    koaBody({
      multipart: true, //解析多个文件
      formidable: {
        maxFileSize: 2 * 1024 * 1024, // 设置上传文件大小最大限制，默认2M
        uploadDir: path.join(__dirname, `public/upload`), // 设置文件上传目录
        keepExtensions: true,
        onFileBegin: (name: string, file: any) => {
          let pname =
            Math.random().toString(36).substring(2) +
            Date.now() +
            file.originalFilename;
          if (name == "imgs") {
            file.filepath = path.join(
              __dirname,
              `public/upload/avator/${pname}`
            );
            app.context.uploadpath = `upload/avator/${pname}`;
          } else if (name == "fbimgs") {
            file.filepath = path.join(
              __dirname,
              `public/upload/fbimg/${pname}`
            );
            app.context.uploadpath = `upload/fbimg/${pname}`;
          } else if (name == "bem") {
            file.filepath = path.join(__dirname, `public/bemimages/${pname}`);
            app.context.uploadpath = `bemimages/${pname}`;
          }

          // console.log(name);
          // console.log(file.filepath);
          //随机时间文件夹名称
          // const date = new Date();
          // let month = date.getMonth() + 1;
          // month =
          //   month.toString().length > 1
          //     ? (month as number)
          //     : (`0${month}` as any);
          // const diri = `${date.getFullYear()}${month}${date.getDate()}`;
          // //拼接文件夹路径
          // const diro = path.join(__dirname, `public/upload/${diri}`);
          // if (!fs.existsSync(diro)) {
          //   fs.mkdirSync(diro);
          // }
          // //设置文件存储文件夹路径
          // file.filepath = `${diro}/${file.newFilename}`;
        },
      },
      onError: (err: Error) => {
        geterrorLogger.error("error", err);
      },
    })
  )
  .use(
    views(__dirname + "/views", {
      extension: "ejs",
    })
  )
  .use(router.routes())
  .use(weChatrouter.routes())
  .use(newsRouter.routes())
  .use(userRouter.routes())
  .use(bemRouter.routes())
  .use(bhRouter.routes())
  .use(router.allowedMethods());
const run = (port: number | String): Server => {
  return app.listen(port, () => {
    console.log("服务已成功运行");
    bemModel.find({ role: "超级管理员" }).then((res) => {
      if (res.length == 0) {
        bemModel
          .create({
            phone: "17516211205",
            role: "超级管理员",
            btnrole: [
              "add",
              "delete",
              "alldelete",
              "distribute",
              "refresh",
              "modify",
              "pq"
            ],
            password: "111",
          })
          .then((res) => {
            console.log("====================================");
            console.log("admin 初始化成功");
            console.log("====================================");
            bemRoleModel
              .create({
                rolename: "超级管理员",
                role: [
                  "/home",
                  "/news",
                  "/newslist",
                  "/newscheck",
                  "/newsmanagement",
                  "/roles",
                  "/roleslist",
                  "/menuslist",
                  "/roleuser",
                  "/rolelist",
                  "/user",
                  "/userslist",
                  "/usersmanagement",
                ],
              })
              .then(async (res) => {
                console.log("====================================");
                console.log('role 初始化成功');
                console.log("====================================");
                let ress = await mem.find();
                if (ress.length == 0) {
                  mem
                    .create({
                      name: "顶级菜单",
                      level: 0,
                      path: "/xxx",
                      parentId: 0,
                    })
                    .then(async (res) => {

                      await mem
                        .create({
                          name: "菜单列表",
                          level: 0,
                          path: "menuslist",
                          parentId: res._id,
                          desc: 'menusView'
                        })
                        .then((ress) => {
                          console.log("====================================");
                          console.log("顶级菜单初始化成功");
                          console.log("====================================");




                        });


                    });
                }
              })
              .catch((err) => {
                console.log("====================================");
                console.log(err);
                console.log("====================================");
              });
          });
      }
    });
  });
};
app.on("error", (err: any, ctx: Context) => {
  geterrorLogger.error("error", err);
  console.error("server error", err);
  resp.error(ctx, err);
});
export { run };
